package mymyoux.graphics.graphicfactoryClasses
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.getDefinitionByName;
	
	import mx.controls.ProgressBar;
	
	import mymyoux.events.MEventDispatcherLocal;
	import mymyoux.graphics.GraphicFactory;
	/**
	 * Parse le XML contenant l'interface.
	 */
	public class Parser extends MEventDispatcherLocal
	{
		 /**
         * Cet évènement est dispatché lorsque le parsage est terminé
         * @eventType flash.events.Event
         */
        [Event(name="end", type="flash.events.Event")]
		static public const END:String="end";
		protected var factory:GraphicFactory;
		protected var xml:XML;
		protected var loadingLibs:uint;
		protected var parent:*;
		public function Parser(factory:GraphicFactory,xml:XML,parent:*=null)
		{
			this.parent=parent;
			this.factory=factory;
			this.xml=xml;
			loadingLibs=0;
			loadLibrary();
		}

		protected function loadLibrary():void
		{
			var x:XML;
			var xmllib:XMLList=xml.lib;
			for each (x in xmllib)
			{
				loadingLibs++;
				var ldr:Loader = new Loader();
	            var req:URLRequest = new URLRequest(x.@url);
	            var ldrContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
	            ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeLibrary);
	            ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,errorLibrary);
	            ldr.load(req,/*null);//*/ ldrContext);
			}
			if(loadingLibs==0)
			{
				//finlibrary
				loadGraphics();	
			}
		}
		protected function completeLibrary(event:Event):void
		{
			loadingLibs--;
			if(loadingLibs==0)
			{
				//nécessaire sinon certaines classes ne sont pas chargées !?
				flash.utils.setTimeout(loadGraphics,100);
			}
			
		}
		protected function errorLibrary(event:IOErrorEvent):void
		{
			/*trace(event);
			trace((event.target as LoaderInfo).url.substring((event.target as LoaderInfo).url.lastIndexOf("/")+1)+" ERROR");*/
			trace("Error : Bibliothèque introuvable!");
		}
		protected function loadGraphics():void
		{
			var xlist:XMLList=xml.item;/*
			var x:XML;
			for each(x in xlist)
			{
				try
				{
					trace(x.@type);
					trace("children : ["+x.item.toXMLString()+"]");
					ApplicationDomain.currentDomain.getDefinition(x.@type);
					
					var c:Class=getDefinitionByName(x.@type) as Class;
					var p:*=new c();
					factory.addChild(p);
					//_sprite.addChild(p);
				}
				catch(error:Error)
				{
					trace("Error parsing ["+x.@type+"]:" +error);
				}
			}*/
			loadingGraphics(xlist,parent);
			this.dispatchEvent(new Event(END));
		}
		/**
		 * Définit les propriétés de l'objet parent.
		 * @param xlist XML contenant les propriétés à parser.
		 * @param parent Objet à qualifier.
		 */
		protected function loadingParams(xlist:XMLList,parent:*):void
		{
			var x:XML;
			var value:String;
			for each(x in xlist)
			{
				try
				{
					//choix entre l'attribut value et le fils / value prioritaire
					value=x.@value.toString().length>0?x.@value.toString():x.children()[0].toString();
					switch(x.@type.toString().toLowerCase())
					{
						case "boolean":
							parent[x.@name]=value=="true";
						break;
						case "string":
							parent[x.@name]=value;
						break;
						case "int":
							parent[x.@name]=int(Number(value));
						break;
						case "uint":
							parent[x.@name]=uint(Number(value));
						break;
						case "number":
							parent[x.@name]=Number(value);
						break;
						case "array":
							parent[x.@name]=value.split(x.@delimiter);
						break;
						default:
							trace("Objet complexe : "+x.@type+" : "+value);
					}
				}catch(error:Error)
				{
					trace("Error param parsing ["+x.@name+"]:" +error);
				}
			}
		}
		protected function loadingEvents(xlist:XMLList,parent:*):void
		{
			var x:XML;
			var value:String;
			for each(x in xlist)
			{
				factory.addEvent(parent,x.@name,x.@value);
			}
		}
		protected function loadingGraphics(xlist:XMLList,parent:*):void
		{
			var x:XML;
			var attr:String;
			for each(x in xlist)
			{
				try
				{				
					ApplicationDomain.currentDomain.getDefinition(x.@type);
					var c:Class=getDefinitionByName(x.@type) as Class;
					new ProgressBar();
					var p:*=new c();
					factory.addChild(p,x.@name,parent,x);
					/*for(attr in x.)
					{
						trace(">>>"+attr);
					}*/
			//		trace(describeType(p).toXMLString());
					loadingParams(x.param,p);
					loadingGraphics(x.item,p);
					loadingEvents(x.event,p);
					//_sprite.addChild(p);
				}
				catch(error:Error)
				{
					trace("Error parsing ["+x.@type+"]:" +error);
				}
			}
			
	
		}

	}
}